|
Download
FAQ History |
|
API
Search Feedback |
Writing Simple JMS Client Applications
This section shows how to create, package, and run simple JMS client programs packaged as standalone J2EE application clients. These clients access a server based on J2EE technology ("J2EE server"). The clients demonstrate the basic tasks that a JMS application must perform:
In a J2EE application, some of these tasks are performed, in whole or in part, by the container. If you learn about these tasks, you will have a good basis for understanding how a JMS application works on the J2EE platform.
The section covers the following topics:
Each example uses two programs: one that sends messages and one that receives them. You can run the programs in two terminal windows.
When you write a JMS application to run in a J2EE application, you use many of the same methods in much the same sequence as you do for a standalone application client. However, there are some significant differences. Using the JMS API in a J2EE Application describes these differences, and the next chapter provides examples that illustrate them.
Setting Your Environment for Running Applications
Before you can run the examples, you need to ensure that your environment is set appropriately. Table 20-3 shows how to set the environment variables needed to run J2EE applications on Microsoft Windows and UNIX platforms.
When you install the tutorial, a
build.propertiesfile is created in the directory<INSTALL>/j2eetutorial14/. In this file, the propertyj2ee.homeis set to the location of your J2EE Application Server installation.The examples for this section are in the following directory:
A Simple Example of Synchronous Message Receives
This section describes the sending and receiving programs in an example that uses the
receivemethod to consume messages synchronously. This section then explains how to compile, package, and run the programs, using the J2EE 1.4 Application Server.The following sections describe the steps in creating and running the example:
Writing the Client Programs
The sending program,
SimpleProducer.java, performs the following steps:
- Performs a JNDI lookup of the
ConnectionFactoryandDestination:
/*
* Create a JNDI API InitialContext object if none exists
* yet.
*/
try {
jndiContext = new InitialContext();
} catch (NamingException e) {
System.out.println("Could not create JNDI API " +
"context: " + e.toString());
System.exit(1);
}
/*
* Look up connection factory and destination. If either
* does not exist, exit. If you look up a
* TopicConnectionFactory instead of a
* QueueConnectionFactory, program behavior is the same.
*/
try {
connectionFactory = (ConnectionFactory)
jndiContext.lookup("jms/QueueConnectionFactory");
if (destType.equals("queue")) {
dest = (Queue) jndiContext.lookup(destName);
} else if (destType.equals("topic")) {
dest = (Topic) jndiContext.lookup(destName);
} else {
throw new Exception("Invalid destination type" +
"; must be queue or topic");
}
} catch (Exception e) {
System.out.println("JNDI API lookup failed: " +
e.toString());
System.exit(1);
}- Creates a
Connectionand aSession:
connection = connectionFactory.createConnection();
session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);- Creates a
MessageProducerand aTextMessage:
producer = session.createProducer(dest);
message = session.createTextMessage();- Sends one or more messages to the destination:
for (int i = 0; i < NUM_MSGS; i++) {
message.setText("This is message " + (i + 1));
System.out.println("Sending message: " +
message.getText());
producer.send(message);
}- Sends an empty control message to indicate the end of the message stream:
producer.send(session.createMessage());- Closes the connection in a
finallyblock, automatically closing the session andMessageProducer:
} finally {
if (connection != null) {
try {
connection.close();
} catch (JMSException e) {}
}
}The receiving program,
SimpleSynchConsumer.java, performs the following steps:
- Performs a JNDI lookup of the
ConnectionFactoryandDestination.- Creates a
Connectionand aSession- Creates a
MessageConsumer:
consumer = session.createConsumer(dest);- Starts the connection, causing message delivery to begin:
connection.start();- Receives the messages sent to the destination until the end-of-message-stream control message is received:
while (true) {
Message m = consumer.receive(1);
if (m != null) {
if (m instanceof TextMessage) {
message = (TextMessage) m;
System.out.println("Reading message: " +
message.getText());
} else {
break;
}
}
}- Closes the connection in a
finallyblock, automatically closing the session andMessageConsumer.The
receivemethod can be used in several ways to perform a synchronous receive. If you specify no arguments or an argument of0, the method blocks indefinitely until a message arrives:For a simple client program, this may not matter. But if you do not want your program to consume system resources unnecessarily, use a timed synchronous receive. Do one of the following:
The
SimpleSynchConsumerprogram uses an indefinitewhileloop to receive messages, callingreceivewith a timeout argument. CallingreceiveNoWaitwould have the same effect.Compiling the Clients
You can compile the examples using the
asanttool.To compile the examples, do the following.
- Verify that you have set the environment variables shown in Table 20-3.
- In a terminal window, go to the following directory:
<INSTALL>/j2eetutorial14/examples/jms/simple/- Type the following command:
asant buildThis command uses the
build.xmlfile in thesimpledirectory to compile all the source files in the directory. The class files are placed in thebuilddirectory.Starting the JMS Provider
When you use the J2EE Application Server, your JMS provider is the Application Server. Start the server as follows:
Creating the JMS Administered Objects for the Simple Examples
If you are in a hurry, you can create the administered objects described in this section by using the following
asanttarget:This target is in the file
<INSTALL>/j2eetutorial14/examples/jms/common/targets.xml, so you can use it from any of the JMS examples directories.To create these objects manually, use the
asadmincommand. The following commands create two connection factories:asadmin create-jms-resource --user admin --resourcetype javax.jms.QueueConnectionFactory --property imqAddressList=localhost jms/QueueConnectionFactory asadmin create-jms-resource --user admin --resourcetype javax.jms.TopicConnectionFactory --property imqAddressList=localhost jms/TopicConnectionFactoryThe following
asadmincommands create a queue whose JNDI name isjms/Queueand a topic whose JNDI name isjms/Topic.asadmin create-jmsdest --user admin --desttype queue PhysicalQueue asadmin create-jms-resource --user admin --resourcetype javax.jms.Queue --property imqDestinationName=PhysicalQueue jms/Queue asadmin create-jmsdest --user admin --desttype topic PhysicalTopic asadmin create-jms-resource --user admin --resourcetype javax.jms.Topic --property imqDestinationName=PhysicalTopic jms/TopicAfter you create these objects, reconfigure the server, then stop and restart the server:
To verify that the destinations and resources have been created, use the following commands:
Packaging the Clients
In order to run these examples using the J2EE Application Server, you need to package each one in a standalone client JAR file.
First, start the J2EE Deploytool:
Package the SimpleProducer example as follows:
- Choose File
New
Application Client JAR to start the Application Client Wizard.
- Select the radio button labeled Create New Stand-Alone AppClient Module.
- Click Browse next to the AppClient Location field and navigate to the
<INSTALL>/j2eetutorial14/examples/jms/simple/directory.- Type
SimpleProducerin the File Name field.- Type
SimpleProducerin the AppClient Display Name field.- Click the Edit button next to the Contents text area.
- In the dialog box, locate the
builddirectory. SelectSimpleProducer.classfrom the Available Files tree area and click Add, then OK- In the General screen, select
SimpleProducerin the Main Class combo box.- Click Next.
- Click Finish.
Package the SimpleSynchConsumer example the same way, except for the following:
- In Step 4, type
SimpleSynchConsumer.jarin the File Name field.- In Step 5, type
SimpleSynchConsumerin the AppClient Display Name field.- In Step 7, select
SimpleSynchConsumer.classfrom the Available Files tree area and click Add, then OK.- In Step 8, select
SimpleSynchConsumerin the Main Class combo box.Running the Clients
You run the sample programs using the appclient command. Each of the programs takes command-line arguments: a destination name, a destination type, and, for SimpleProducer, a number of messages.
Run the clients as follows.
- Run the
SimpleProducerprogram, sending three messages to the queuejms/Queue:
appclient -client SimpleProducer.jar jms/Queue queue 3The output of the program looks like this, along with some output from the AppClient container:
Destination name is jms/Queue, type is queue
Sending message: This is message 1
Sending message: This is message 2
Sending message: This is message 3The messages are now in the queue, waiting to be received.
- In the same window, run the
SimpleSynchConsumerprogram, specifying the queue name and type:
appclient -client SimpleSynchConsumer.jar jms/Queue queueThe output of the program looks like this:
Destination name is jms/Queue, type is queue
Reading message: This is message 1
Reading message: This is message 2
Reading message: This is message 3- Now try running the programs in the opposite order. Run the
SimpleSynchConsumerprogram. It displays the queue name and then appears to hang, waiting for messages.- In a different terminal window, run the
SimpleProducerprogram. When the messages have been sent, theSimpleSynchConsumerprogram receives them and exits.- Now run the
SimpleProducerprogram using a topic instead of a queue. On a Microsoft Windows system, the command looks like this:
appclient -client SimpleProducer.jar jms/Topic topic 3The output of the program looks like this:
Destination name is jms/Topic, type is topic
Sending message: This is message 1
Sending message: This is message 2
Sending message: This is message 3- Now run the
SimpleSynchConsumerprogram using the topic. On a Microsoft Windows system, the command looks like this:
appclient -client SimpleSynchConsumer.jar jms/Topic topicThe result, however, is different. Because you are using a topic, messages that were sent before you started the consumer cannot be received. (See Publish/Subscribe Messaging Domain, for details.) Instead of receiving the messages, the program appears to hang.
- Run the
SimpleProducerprogram again in another terminal window. Now theSimpleSynchConsumerprogram receives the messages:
Destination name is jms/Topic, type is topic
Reading message: This is message 1
Reading message: This is message 2
Reading message: This is message 3A Simple Example of Asynchronous Message Consumption
This section describes the receiving programs in an example that uses a message listener to consume messages asynchronously. This section then explains how to compile and run the programs, using the J2EE 1.4 Application Server.
The following sections describe the steps in creating and running the example:
Writing the Client Programs
The sending program is
SimpleProducer.java, the same program used in the example in A Simple Example of Synchronous Message Receives. You may, however, want to comment out the following line of code, where the producer sends a non-text control message to indicate the end of the messages:An asynchronous consumer normally runs indefinitely. This one runs until the user types the letter
qorQto stop the program, so it does not use the non-text control message.The receiving program,
SimpleAsynchConsumer.java, performs the following steps:
- Performs a JNDI lookup of the
ConnectionFactoryandDestination- Creates a
Connectionand aSession- Creates a
MessageConsumer- Creates an instance of the
TextListenerclass and registers it as the message listener for theMessageConsumer:
listener = new TextListener();
consumer.setMessageListener(listener);- Starts the connection, causing message delivery to begin
- Listens for the messages published to the destination, stopping when the user types the character
qorQ:
System.out.println("To end program, type Q or q, " +
"then <return>");
inputStreamReader = new InputStreamReader(System.in);
while (!((answer == 'q') || (answer == 'Q'))) {
try {
answer = (char) inputStreamReader.read();
} catch (IOException e) {
System.out.println("I/O exception: "
+ e.toString());
}
}- Closes the connection, which automatically closes the session and
MessageConsumerThe message listener,
TextListener.java, follows these steps:
- When a message arrives, the
onMessagemethod is called automatically.- The
onMessagemethod converts the incoming message to aTextMessageand displays its content. If the message is not a text message, it reports this fact:
public void onMessage(Message message) {
TextMessage msg = null;
try {
if (message instanceof TextMessage) {
msg = (TextMessage) message;
System.out.println("Reading message: " +
msg.getText());
} else {
System.out.println("Message is not a " +
"TextMessage");
}
} catch (JMSException e) {
System.out.println("JMSException in onMessage(): " +
e.toString());
} catch (Throwable t) {
System.out.println("Exception in onMessage():" +
t.getMessage());
}
}Compiling the Clients
To compile the example, do the following.
- Verify that you have set the environment variables shown in Table 20-3.
- Compile the programs if you did not do so before or if you edited
SimpleProducer.javaas described in Writing the Client Programs:
asant buildStarting the JMS Provider
If you did not do so before, start the J2EE Application Server in another terminal window.
You will use the connection factories and destinations you created in Creating the JMS Administered Objects for the Simple Examples.
Packaging the SimpleAsynchConsumer Client
If you did not do so before, start the J2EE Deploytool.
Package the SimpleAsynchConsumer example as follows:
- Choose File
New
Application Client JAR to start the Application Client Wizard.
- Select the radio button labeled Create New Stand-Alone AppClient Module.
- Click Browse next to the AppClient Location field and navigate to the
<INSTALL>/j2eetutorial14/examples/jms/simple/directory.- Type
SimpleAsynchConsumerin the File Name field.- Type
SimpleAsynchConsumerin the AppClient Display Name field.- Click the Edit button next to the Contents text area.
- In the dialog box, locate the
builddirectory. SelectSimpleAsynchConsumer.classandTextListener.classfrom the Available Files tree area and click Add, then OK- In the General screen, select
SimpleAsynchConsumerin the Main Class combo box.- Click Next.
- Click Finish.
If you did not already package the SimpleProducer program, do so by following the instructions in Packaging the Clients.
Running the Clients
As before, you run the sample programs using the
appclientcommand.Run the clients as follows.
- Run the
SimpleAsynchConsumerprogram, specifying the topicjms/Topicand its type.
appclient -client SimpleAsynchConsumer.jar jms/Topic topicThe program displays the following lines and appears to hang:
Destination name is jms/Topic, type is topic
To end program, type Q or q, then <return>- In another terminal window, run the
SimpleProducerprogram, sending three messages. The commands look like this:
appclient -client SimpleProducer.jar jms/Topic topic 3The output of the program looks like this:
Destination name is jms/Topic, type is topic
Sending message: This is message 1
Sending message: This is message 2
Sending message: This is message 3In the other window, the
SimpleAsynchConsumerprogram displays the following:
Destination name is jms/Topic, type is topic
To end program, type Q or q, then <return>
Reading message: This is message 1
Reading message: This is message 2
Reading message: This is message 3If you did not edit
SimpleProducer.java, the following line also appears:
Message is not a TextMessage- Type
Qorqto stop the program.- Now run the programs using a queue. In this case, as with the synchronous example, you can run the
SimpleProducerprogram first, because there is no timing dependency between the sender and receiver:
appclient -client SimpleProducer.jar jms/Queue queue 3The output of the program looks like this:
Destination name is jms/Queue, type is queue
Sending message: This is message 1
Sending message: This is message 2
Sending message: This is message 3- Run the
SimpleAsynchConsumerprogram:
appclient -client SimpleAsynchConsumer.jar jms/Queue queueThe output of the program looks like this:
Destination name is jms/Queue, type is queue
To end program, type Q or q, then <return>
Reading message: This is message 1
Reading message: This is message 2
Reading message: This is message 3- Type
Qorqto stop the program.Running JMS Client Programs on Multiple Systems
JMS client programs can communicate with each other when they are running on different systems in a network. The systems must be visible to each other by name--the UNIX host name or the Microsoft Windows computer name--and must both be running the J2EE server. You do not have to install the tutorial on both systems; you can use the tutorial installed on
earthif you have access to the file system onearth.Suppose that you want to run the
SimpleProducerprogram on one system,mars, and theSimpleSynchConsumerprogram on another system,earth. To do so, follow these steps.
- Start the J2EE Application Server on
earth.- Start the J2EE Application Server on
mars.- On
earth, create aQueueConnectionFactoryobject, using the followingasanttarget:
asant add-local-factoryThis command creates a connection factory named
jms/EarthQueueConnectionFactory.- On
mars, create a connection factory with the same name that points to the server onearth. Use the following command, replacingsys-namewith the name of your remote system:
asadmin create-jms-resource --resourcetype
javax.jms.QueueConnectionFactory --property
imqAddressList=sys-namejms/EarthQueueConnectionFactoryYou can also use the
asanttargetadd-remote-factory.If the JMS service on the remote system uses a port number other than the default (7676), use the syntax
imqAddressList=sys-name:port-number.- Reconfigure the server:
asant reconfig_common- Stop and restart the server.
- To verify that the factories were created, use the following command:
asadmin list-jms-resources --user admin- In each source program, change the line that looks up the connection factory so that it refers to the new connection factory:
connectionFactory = (ConnectionFactory)
jndiContext.lookup("jms/EarthQueueConnectionFactory");- Recompile the programs:
asant build- Repackage the
SimpleProducerandSimpleSynchConsumerprograms as described in Packaging the Clients. Name the filesProducerRemote.jarandSynchConsumerRemote.jarif you don't want to overwrite the other JAR files.- Run
SimpleProduceronmars:
appclient -client ProducerRemote.jar jms/Queue queue 3- Run
SimpleSynchConsumeronearth:
appclient -client SynchConsumerRemote.jar jms/Queue queueBecause both connection factories have the same name, you can run either the producer or the consumer on either system. (Note: A bug in the JMS provider in the J2EE Application Server may cause a runtime failure to create a connection to systems that use the Dynamic Host Configuration Protocol [DHCP] to obtain an IP address.)
For examples showing how to deploy J2EE applications on two different systems, see An Application Example that Consumes Messages from a Remote J2EE Server and An Application Example that Deploys a Message-Driven Bean on Two J2EE Servers.
Deleting the Connection Factory and Stopping the Server
You will need the connection factory
jms/EarthQueueConnectionFactoryin the next chapter. However, if you wish to delete it, use the following command:Remember to delete the connection factory on both systems.
You can use the
delete-resourcestarget to delete the destinations and connection factories you created in Creating the JMS Administered Objects for the Simple Examples. However, we recommend that you keep them, because they will be used in most of the JMS examples. Once you have created them, they will be available whenever you restart the J2EE Application Server.Delete the class files for the programs as follows:
If you wish, you can manually delete the client JAR files.
You can stop the J2EE Application Server as well, but you will need it to run the sample programs in the next section.
|
Download
FAQ History |
|
API
Search Feedback |
All of the material in The J2EE 1.4 Tutorial is copyright-protected and may not be published in other works without express written permission from Sun Microsystems.